package ru.elifantiev.cityrouter.infrastructure.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class JsonAdapter extends BaseAdapter {

    private JSONArray data;
    private View itemView;
    private int[] viewIds;
    private String[] dataKeys;


    public JsonAdapter(Context ctx, int itemViewResource, JSONArray data, int[] views, String[] keys) {
        this.data = data;
        this.viewIds = views;
        this.dataKeys = keys;
        itemView = LayoutInflater.from(ctx).inflate(itemViewResource, null, false);
    }

    public int getCount() {
        return data.length();
    }

    public JSONObject getItem(int i) {
        try {
            return data.getJSONObject(i);
        } catch (JSONException e) {
            // ignore
        }
        return null;
    }

    public long getItemId(int i) {
        return i;
    }

    public View getView(int i, View view, ViewGroup viewGroup) {
        View ret = view == null ? itemView : view;

        for(int j = 0, l = viewIds.length; j < l; j++) {
            try {
                ((TextView)ret.findViewById(viewIds[j])).setText(getItem(i).getString(dataKeys[j]));
            } catch (JSONException e) {
                // ignore
            }
        }

        return ret;
    }
}
